<template>
	<jk-dialog
		:dialog-state="showDialog"
		:title="`开台-${ruleForm.machineName}`"
		width="900px"
		:confirm-btn-loading="confirmBtnLoading"
		:show-content-loading="showLoading"
		@on-cancel="onVisibleChange(false)"
		@on-confirm="onConfirmBtn"
		@on-visible-change="onVisibleChange"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="140px" :show-message="false">
			<div class="flex-center">
				<el-tag effect="plain" size="large" class="margin-bottom-10" style="font-weight: 700;font-size: 22px;">
					<span class="el-icon-files item-gap"></span>
					<span>{{ ruleForm.machineName }}</span>
				</el-tag>
			</div>
			<jk-divider-card class="margin-top-10">
				<el-row>
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="品种">
							<span class="read-only-2">{{ ruleForm.productName }}</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="批号">
							<span class="read-only-2">{{ ruleForm.batchCode }}</span>
						</el-form-item>
					</el-col>
					<!--<el-col :span="12">
                        <el-form-item class="margin-bottom-10" label="生产订单">
                            <span class="read-only-2">{{ ruleForm.productOrderCode }}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item class="margin-bottom-10" label="排产数量">
                            <span class="read-only-2">{{ ruleForm.productionQty }}</span>
                        </el-form-item>
                    </el-col>-->
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" :label="getColorInfoByProcess(ruleForm.processCode).inputName">
							<span class="read-only-2">{{ ruleForm.inputTubeColorList && ruleForm.inputTubeColorList.length ? ruleForm.inputTubeColorList.map(x => x.name).join(',') : '无' }}</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" :label="getColorInfoByProcess(ruleForm.processCode).outName">
							<span class="read-only-2">{{ ruleForm.outputTubeColorList && ruleForm.outputTubeColorList.length ? ruleForm.outputTubeColorList.map(x => x.name).join(',') : '无' }}</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item class="margin-bottom-0" label="机台锭数">
							<span class="read-only-2">{{ `总数: ${ruleForm.spinCount}, 已使用: ${ruleForm.usedSpinCount}, 剩余：${ruleForm.spinCount - ruleForm.usedSpinCount}` }}</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="生产通知单">
							<span class="read-only-2">{{ ruleForm.prdNoticeCode }}</span>
						</el-form-item>
					</el-col>
				</el-row>
			</jk-divider-card>
			<jk-divider-card title="仪表信息" class="margin-top-30">
				<el-row class="flex-start-center-wrap">
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="开台时间" prop="startTime">
							<div class="flex-start-center">
								<el-date-picker v-model="ruleForm.startTime" clearable type="datetime" style="width: 100%;" value-format="yyyy-MM-dd HH:mm:ss" placeholder="开台时间" @change="onTimeChange" />
								<stopRecordBar
									:form-data="ruleForm"
									@on-confirm="onConfirmBtnOfStopRecordBar"
								></stopRecordBar>
							</div>
						</el-form-item>
					</el-col>
					<!--<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="开台班次">
							<jk-input v-model="ruleForm.startScheduleShiftName" readonly placeholder=""></jk-input>
						</el-form-item>
					</el-col>-->
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="开台锭数">
							<jk-number-input v-model="ruleForm.openSpinCount" placeholder="开台锭数" />
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item class="margin-bottom-10" label="系数" prop="outputRatio">
							<jk-number-input v-model="ruleForm.outputRatio" class="width-100-percent" :max="1" placeholder="系数" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<!--络筒不采集米数，不做必填-->
					<el-col v-show="ruleForm.processCode ? ruleForm.processCode.toUpperCase() === 'LT' : false" :span="12">
						<el-form-item v-if="ruleForm.processCode.toUpperCase() === 'LT'" class="margin-bottom-10" label="开台表数(M)">
							<jk-number-input v-model="ruleForm.startOutput" placeholder="开台表数(M)" />
						</el-form-item>
					</el-col>
					<el-col v-show="ruleForm.processCode ? ruleForm.processCode.toUpperCase() !== 'LT' : false" :span="12">
						<el-form-item v-if="ruleForm.processCode.toUpperCase() !== 'LT'" class="margin-bottom-10" label="开台表数(M)" prop="startOutput">
							<jk-number-input v-model="ruleForm.startOutput" placeholder="开台表数(M)" />
						</el-form-item>
					</el-col>
					<!--<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="产量系统表数(M)">
							<el-input v-model="ruleForm.startSystemOutput" disabled placeholder="产量系统表数(M)" />
						</el-form-item>
					</el-col>-->
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="开台表数(kg)">
							<jk-number-input v-model="ruleForm.startOutputKg" placeholder="开台表数(kg)" />
						</el-form-item>
					</el-col>
					<!--<el-col :span="12">
                        <el-form-item class="margin-bottom-10" label="产量系统表数(kg)">
                            <el-input v-model="ruleForm.startSystemOutputKg" disabled placeholder="产量系统表数(kg)" />
                        </el-form-item>
                    </el-col>-->
					<el-col :span="12">
						<el-form-item class="margin-bottom-0" label="开台能耗表数" prop="startElectricEnergy1">
							<jk-number-input v-model="ruleForm.startElectricEnergy" placeholder="开台能耗表数" />
						</el-form-item>
					</el-col>
					<!--<el-col :span="12">
                        <el-form-item class="margin-bottom-0" label="能耗表数">
                            <el-input v-model="ruleForm.startSystemElectricEnergy" disabled placeholder="能耗表数" />
                        </el-form-item>
                    </el-col>-->
				</el-row>
			</jk-divider-card>
		</el-form>

	</jk-dialog>
</template>

<script>
    import { clearRedundancyKey, formatTime, tipsBar } from '../../../../utils/jk/jk-tool';
    import { mathJsSub } from '../../../../utils/jk/jk-cals';
    import {
        productionPrdNoticeMachineChangeGetMachineData,
        productionPrdNoticeMachineOpeningCheckOpening,
        productionPrdNoticeMachineOpeningCompleteRenovationOpening,
        productionPrdNoticeMachineOpeningOpening
    } from '../../../../api/production/xsOpen';
    import getTubeColor from '../../foreSpinPrd/foreSpinningPlan/components/form-box/get-tube-color';
    import stopRecordBar from './stopRecordBar';
    export default {
        components: {
            stopRecordBar
        },
        mixins: [getTubeColor],
        props: {
            /**
             * @操作类型：
             *  1、开台
             *  2、完成翻改并开台;
             *
             * */
            operationType: {
                type: Number,
                default: 1
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            selectMachineItem: {
                type: Object,
                default() {
                    return {};
                }

            }
        },
        data() {
            return {
                showLoading: false,
                activeName: '1',
                showDialog: false,
                confirmBtnLoading: false,
                ruleForm: {
                    'processCode': '',
                    'startOutputKg': 0,
                    'startSystemOutputKg': 0,
                    'outputRatio': 1,
                    'endSpinNumber': null,
                    'lastEndElectricEnergy': null,
                    'lastEndOutput': null,
                    'openSpinCount': null,
                    'prdNoticeMachineChangeId': null,
                    'startElectricEnergy': null,
                    'startOutput': null,
                    'startScheduleShiftId': null,
                    'startScheduleShiftName': '',
                    'startSpinNumber': null,
                    'startSystemElectricEnergy': null,
                    'startSystemOutput': null,
                    'startSystemTime': '',
                    'startTime': '',
                    'spinCount': 0, // 机台的设定锭数
                    'usedSpinCount': 0 // 已经开台的锭数
                },
                rules: {
                    startScheduleShiftName: [{ required: true, trigger: 'change' }],
                    openSpinCount: [{ required: true, trigger: 'change' }],
                    startTime: [{ required: true, trigger: 'change' }],
                    startOutput: [{ required: true, trigger: 'change' }],
                    startElectricEnergy: [{ required: true, trigger: 'change' }]
                }
            };
        },
        methods: {
            onTimeChange() {
                this.$set(this.ruleForm, 'startScheduleShiftId', null);
                this.$set(this.ruleForm, 'startScheduleShiftName', '');
                this.getScheduleShiftForTimeRequest();
                this.getGatherMachineDataRequest();
            },
            onConfirmBtnOfStopRecordBar(item) {
                if (Object.keys(item).length) {
                    this.$set(this.ruleForm, 'startTime', JSON.parse(JSON.stringify(item)).systemStartDateTime);
                    this.onTimeChange();
                } else {
                    tipsBar(this, 'custom', 'warning', '请选择!');
                }
            },
            onJump() {
                this.$toMainRouter({
                    name: 'XsClose',
                    query: {
                        machineCode: this.ruleForm.machineCode
                    }
                });
            },
            onSpinNumChange() {
                if (this.ruleForm.endSpinNumber) {
                    this.ruleForm.startSpinNumber = this.ruleForm.startSpinNumber || 0;
                    this.$set(this.ruleForm, 'openSpinCount', mathJsSub(this.ruleForm.endSpinNumber, this.ruleForm.startSpinNumber));
                }
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        const params = {
                            'outputRatio': this.ruleForm.outputRatio,
                            'endSpinNumber': this.ruleForm.endSpinNumber,
                            'lastEndElectricEnergy': this.ruleForm.lastEndElectricEnergy,
                            'lastEndOutput': this.ruleForm.lastEndOutput,
                            'openSpinCount': this.ruleForm.openSpinCount,
                            'prdNoticeMachineChangeId': this.ruleForm.prdNoticeMachineChangeId,
                            'startElectricEnergy': this.ruleForm.startElectricEnergy,
                            'startOutput': this.ruleForm.startOutput,
                            // 'startScheduleShiftId': this.ruleForm.startScheduleShiftId,
                            'startSpinNumber': this.ruleForm.startSpinNumber,
                            'startSystemElectricEnergy': this.ruleForm.startSystemElectricEnergy,
                            'startSystemOutput': this.ruleForm.startSystemOutput,
                            'startSystemTime': this.ruleForm.startSystemTime,
                            'startTime': this.ruleForm.startTime,

                            'startOutputKg': this.ruleForm.startOutputKg,
                            'startSystemOutputKg': this.ruleForm.startSystemOutputKg
                        };

                        // 校验与采集的品种是否一致
                        productionPrdNoticeMachineOpeningCheckOpening([params]).then(res => {
                            if (res.data.status === 200) {
                                const resData = res.data.res || [];
                                if (resData && resData.length) {
                                    const warningInfo = resData[0];
                                    this.$msgbox({
                                        title: '提示',
                                        message: `品种不一致，设备品种:"${warningInfo.machineProductName}"，计划品种:"${warningInfo.planProductName}"，确认继续"开台"吗？`,
                                        iconClass: 'el-icon-question',
                                        showCancelButton: true,
                                        confirmButtonText: '确定',
                                        cancelButtonText: '取消',
                                        beforeClose: (action, instance, done) => {
                                            if (action === 'confirm') {
                                                done();
                                                this.saveRequest(params);
                                            } else {
                                                done();
                                            }
                                        }
                                    });
                                } else {
                                    this.saveRequest(params);
                                }
                            }
                        });
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            saveRequest(params) {
                this.confirmBtnLoading = true;
                // operationType: 1"开台", 否则表示"完成翻改并开台"
                const api = this.operationType === 1 ? productionPrdNoticeMachineOpeningOpening : productionPrdNoticeMachineOpeningCompleteRenovationOpening;
                api(params).then(res => {
                    this.confirmBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$emit('on-confirm');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
            },
            getScheduleShiftForTimeRequest() {
                if (this.ruleForm.workshopId && this.ruleForm.startTime) {
                    /* return workforcemanagementScheduleShiftByTime({
                        startTime: this.ruleForm.startTime,
                        workshopId: this.ruleForm.workshopId
                    }).then(res => {
                        if (res.data.status === 200) {
                            let resData = res.data.res;
                            if (!resData) {
                                tipsBar(this, 'custom', 'warning', '当前时间未排班，请排班后再操作！');
                                resData = { shiftId: null, shiftName: '' };
                            }
                            this.$set(this.ruleForm, 'startScheduleShiftId', resData.shiftId);
                            this.$set(this.ruleForm, 'startScheduleShiftName', resData.shiftName);
                        }
                    });*/
                }
            },
            // 获取指定机台采集的仪表数据
            getGatherMachineDataRequest() {
                if (this.ruleForm.machineCode && this.ruleForm.startTime) {
                    return productionPrdNoticeMachineChangeGetMachineData({
                        machineId: this.ruleForm.machineId,
                        machineCode: this.ruleForm.machineCode,
                        selectDateTime: this.ruleForm.startTime
                    }).then(res => {
                        if (res.data.status === 200) {
                            // 开台能耗表数，默认等于采集到的实时能耗
                            this.$set(this.ruleForm, 'startElectricEnergy', res.data.res.currentElectricEnergy);
                            this.$set(this.ruleForm, 'startSystemElectricEnergy', res.data.res.currentElectricEnergy);
                            // 开台表数(M)，默认等于采集到的实时产量
                            this.$set(this.ruleForm, 'startOutput', res.data.res.currentOutput);
                            this.$set(this.ruleForm, 'startSystemOutput', res.data.res.currentOutput);
                            // 上次的产量和能耗
                            this.$set(this.ruleForm, 'lastEndOutput', res.data.res.lastEndOutput);
                            this.$set(this.ruleForm, 'lastEndElectricEnergy', res.data.res.lastEndElectricEnergy);

                            this.$set(this.ruleForm, 'openSpinCount', res.data.res.spinCount - res.data.res.usedSpinCount);
                            this.$set(this.ruleForm, 'usedSpinCount', res.data.res.usedSpinCount);
                            this.$set(this.ruleForm, 'spinCount', res.data.res.spinCount);

                            this.$set(this.ruleForm, 'startOutputKg', res.data.res.currentOutputKg);
                            this.$set(this.ruleForm, 'startSystemOutputKg', res.data.res.currentOutputKg);
                        }
                    });
                }
            },
            async getDependentData() {
                this.showLoading = true;
                await this.getScheduleShiftForTimeRequest();
                await this.getGatherMachineDataRequest();
                this.$nextTick(() => {
                    this.$refs.ruleForm.clearValidate();
                });
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.ruleForm = clearRedundancyKey(this.selectMachineItem);
                this.$set(this.ruleForm, 'spinCount', 0);
                this.$set(this.ruleForm, 'usedSpinCount', 0);
                this.$set(this.ruleForm, 'prdNoticeMachineChangeId', this.selectMachineItem.id);
                this.$delete(this.ruleForm, 'id');
                // 漏开警告时会赋值最近的一次翻改时间,否则默认当前时间
                if (!this.ruleForm.startTime) {
                    this.$set(this.ruleForm, 'startSystemTime', formatTime(Date.now()));
                    this.$set(this.ruleForm, 'startTime', formatTime(Date.now()));
                }
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
